package com.igroupes.ovineherd.service.impl;

import com.igroupes.ovineherd.entity.SequenceEntity;
import com.igroupes.ovineherd.enums.SequenceExceptionEnum;
import com.igroupes.ovineherd.exception.OvineHerdException;
import com.igroupes.ovineherd.mapper.SequenceMapper;
import com.igroupes.ovineherd.service.SequenceService;
import com.igroupes.ovineherd.util.EnumUtils;
import com.igroupes.ovineherd.util.Requires;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SequenceServiceImpl implements SequenceService {
    @Autowired
    private SequenceMapper sequenceMapper;

    @Override
    public Long nextValue(String key) {
        Requires.requireNonBlank(key);
        Long ret = sequenceMapper.nextValue(key);
        Requires.requireNonNull(ret);
        if(SequenceExceptionEnum.isError(ret)){
            throw new OvineHerdException(EnumUtils.getEnumByCode(SequenceExceptionEnum.class , ret.intValue()).getErrorCode());
        }
        ;
        return ret;
    }

    @Override
    public void addSequenceRecord(String key, long inc, long min, long max) {
        addSequenceRecord(key, inc, min, min, max);
    }

    @Override
    public void addSequenceRecord(String key, long inc, long value, long min, long max) {
        SequenceEntity sequenceEntity = new SequenceEntity()
                .setCurrentValue(value)
                .setMin(min)
                .setMax(max)
                .setIncrement(inc)
                .setKey(key);
        sequenceMapper.insert(sequenceEntity);

    }

    @Override
    public void addSequenceRecord(String key, long inc, long value, int length) {
        Requires.requireTrue(length>0);
        addSequenceRecord(key, inc, value, getMin(length), getMax(length));
    }

    @Override
    public void addSequenceRecord(String key, long value, int length) {
        addSequenceRecord(key, 1, value, length);
    }

    @Override
    public void addSequenceRecord(String key, int length) {
        Requires.requireTrue(length>0);
        addSequenceRecord(key,getMin(length),length);
    }


    private long getMin(int length){
        return (long) Math.pow(10, length-1);
    }

    private long getMax(int length){
        return (long) Math.pow(10, length)-1;
    }
}
